﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VerbrauchProcessor.DatabaseAccess.DataModel;

namespace VerbrauchProcessor
{
	public class Stats
	{
		/// <summary>
		/// This method creates a list of measurementy intervalls for a given year. 
		/// </summary>
		/// <param name="samples">The samples from which the measurement intervalls shall be created</param>
		/// <param name="sYear">The year by which the measurement intervalls shall be created.</param>
		/// <returns>The list with the measurement intervalls.</returns>
		static public IList<MeasurementIntervall> GetMeasurementIntervallsForYear(IList<Sample> samples, string sYear)
		{

			IList<MeasurementIntervall> resultList = new List<MeasurementIntervall>();
			IList<MeasurementIntervall> measurementIntervallsByYear = new List<MeasurementIntervall>();

			// group by year and month
			var samplesByYear = from sample in samples
									 group sample by sample.Date.Year into measurementsFromOneYear
									 select new
									 {
										 Year = measurementsFromOneYear.Key,
										 SamplesByYear = measurementsFromOneYear,
										 SamplesByMonth = from sample in measurementsFromOneYear
														  group sample by sample.Date.Month into samplesbyMonth
														  select new
														  {
															  Month = samplesbyMonth.Key,
															  Samples = samplesbyMonth
														  }
									 };

			int year;

			// get measure for the wanted year.
			if (Int32.TryParse(sYear, out year) == true)
			{
				foreach (var el in samplesByYear)
				{
					if (el.Year == year)
					{
						measurementIntervallsByYear = GetMeasurementIntervalls((IList<Sample>)el.SamplesByYear);
					
						// interpolate inner samples
						List<Sample> list = new List<Sample>();
						measurementIntervallsByYear.ToList<MeasurementIntervall>().ForEach(mi=>
						{
							list.AddRange(MeasurementIntervall.interpolateSamples(mi));
						});

						// get new intervalls
						resultList = GetMeasurementIntervalls(list);
					}
				}
			}

			return resultList;
		}

		/// <summary>
		/// Computes the average intervalls from a list of samples.
		/// </summary>
		/// <param name="samples">The samples from the data base.</param>
		/// <returns>The measurement intervalls.</returns>
		static public IList<MeasurementIntervall> GetMeasurementIntervalls(IList<Sample> samples)
		{
			IList<MeasurementIntervall> measurementIntervalls = new List<MeasurementIntervall>();

			for (int i = 0; i + 1 < samples.Count; i++)
			{
				Sample firstSample = samples[i];
				Sample secondSample = samples[i + 1];

				MeasurementIntervall measurementIntervall = new MeasurementIntervall(firstSample, secondSample);
				measurementIntervalls.Add(measurementIntervall);
			}

			return measurementIntervalls;
		}
	}
}
